﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace JenkinsCodeBuid.Service
{
    public class IISHelper_Hyyx
    {

        private static List<string> _allSiteList = new List<string>();
        /// <summary>
        /// 要求用户输入 
        /// </summary>
        internal static void QueryUserInput(bool isShowSite = true)
        {
            if (isShowSite)
            {
                ShowAllSite();
            }
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("请输入站点名称");
            string site = Console.ReadLine()?.Trim();
            if (string.IsNullOrEmpty(site))
            {
                QueryUserInput(false);
            }
            else
            {
                StopAndReleaseSite(site);
            }
        }

        /// <summary>
        /// 停止并发布站点
        /// </summary>
        /// <param name="site"></param>
        private static void StopAndReleaseSite(string site)
        {
            //var strOut = ExeCommand($@"C:\Windows\System32\inetsrv\appcmd.exe stop apppool /apppool.name:""{site}""");
            //if (!string.IsNullOrEmpty(strOut) && !strOut.Contains("已停止"))
            //{
            //    Console.WriteLine(strOut);
            //}
            //strOut = ExeCommand($@"C:\Windows\System32\inetsrv\appcmd.exe stop site ""{site}""");
            //if (!string.IsNullOrEmpty(strOut) && !strOut.Contains("已停止"))
            //{
            //    Console.WriteLine(strOut);
            //}
            //Console.WriteLine("停止成功");

            if (!_allSiteList.Any(q => q == site))
            {
                Console.WriteLine($"未找到{site}站点，请在下面站点中复制一个：");
                QueryUserInput(true);
                return;
            }

            var projectName = "WebApi";
            var projectPath = site;
            var hyyxPath = site.Replace("HysEC.", "HysHyyx.");
            if (site.EndsWith("App"))
            {
                projectPath = site.ReplaceLast("App", "");
                projectName = "AppApi";
                var path = $@"C:\Program Files (x86)\Jenkins\workspace\hysyun.hyyx\{projectPath}\{projectPath}.{projectName}";
                if (!System.IO.Directory.Exists(path))
                {
                    projectName = "ClientWebApi";
                }
            }
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"正在发布：{site}.{projectName}，请耐心等待结果...");

            string cmdTxt = $@"
dotnet publish ""C:\Program Files (x86)\Jenkins\workspace\hysyun.hyyx\{projectPath}\{projectPath}.{projectName}\{projectPath}.{projectName}.csproj"" --configuration release  --framework netcoreapp2.2 --runtime win-x64 --output ""D:\WebSite\{hyyxPath}""
xcopy D:\WebSite\HysEC.Src\{site}.Src D:\WebSite\{hyyxPath} /c /y /s
xcopy ""C:\Program Files (x86)\Jenkins\workspace\hysyun.hyyx\{projectPath}\{projectPath}.{projectName}\bin\Debug\netcoreapp2.2\*.xml"" ""D:\WebSite\{hyyxPath}"" /c /y /s
";

            string strOut = ExeCommand(cmdTxt, true);
            Console.WriteLine(strOut);
            Console.WriteLine("发布已结束");


            //strOut = ExeCommand($@"C:\Windows\System32\inetsrv\appcmd.exe start apppool /apppool.name:""{site}""");
            //if (!string.IsNullOrEmpty(strOut))
            //{
            //    Console.WriteLine(strOut);
            //}
            //strOut = ExeCommand($@"C:\Windows\System32\inetsrv\appcmd.exe start site ""{site}""");
            //if (!string.IsNullOrEmpty(strOut))
            //{
            //    Console.WriteLine(strOut);
            //}
            //Console.WriteLine("启动成功");
            QueryUserInput(false);
        }
        /// <summary>
        /// 展示全部站点
        /// </summary>
        private static void ShowAllSite()
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            try
            {
                var strOut = ExeCommand($@"C:\Windows\System32\inetsrv\appcmd.exe list site", true);
                string regex = "\"(.+?)\".+:(\\d+)";
                RegexOptions options = RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline
                            | RegexOptions.IgnoreCase;
                Regex reg = new Regex(regex, options);
                var mas = reg.Matches(strOut);
                List<string> outList = new List<string>();
                foreach (Match item in mas)
                {
                    outList.Add($"{item.Groups[1].Value.Trim()}");
                }
                Console.WriteLine("当前可用的站点：");
                _allSiteList = outList.OrderBy(q => q).ToList();
                foreach (var item in _allSiteList)
                {
                    Console.WriteLine(item);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="commandText"></param>
        /// <param name="needOutPut"></param>
        /// <returns></returns>
        private static string ExeCommand(string commandText, bool needOutPut = false)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            string strOutput = null;
            try
            {
                p.Start();
                p.StandardInput.WriteLine(commandText);
                p.StandardInput.WriteLine("exit");
                strOutput = p.StandardOutput.ReadToEnd();
                if (!strOutput.Contains("ERROR") && !needOutPut)
                {
                    strOutput = "";
                }
                p.WaitForExit();

                p.Close();
            }
            catch (Exception e)
            {
                strOutput = e.Message;
            }
            return strOutput;
        }
    }
}
